
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp \
     import template

class Content(db.Model):
	published = db.BooleanProperty(required=True)			#is article published (on/off)
	timestamp = db.DateTimeProperty(auto_now_add=True)		#last modified
	content = db.TextProperty()								#The content of the post
	title = db.StringProperty(required=True)				#Title of the post
	

class MyHandler(webapp.RequestHandler):
    
    def get(self):
		#query for specific id
		if self.request.get('id'):
			query = Content.get_by_id(int(self.request.get('id')))
			self.response.out.write(template.render('save_content.html', {
					'title': query.title, 
					'published': query.published, 
					'content': query.content, 
					'id': self.request.get('id')
					}))
			
		#show the blank form
		else:
			self.response.out.write(template.render('save_content.html', {}))

			
    def post(self):
	
			#if an existing ID is sent, we must pull existing ID and update
			if self.request.get('id'):
				content = Content.get_by_id(int(self.request.get('id')))
				content.published = bool(self.request.get('published'))
				content.content=self.request.get('content')
				content.title=self.request.get('title')
				
			#create new item
			else:	
				content = Content(published=bool(self.request.get('published')),
							content=self.request.get('content'),
							title=self.request.get('title'))
						
			content.put()
			self.response.out.write(template.render('save_content.html', {}))
			
def main():
    app = webapp.WSGIApplication([(r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()